//
//  ST_FilterOptionSelectView.swift
//  BTVideo
//
//  Created by DouLei on 2019/10/17.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import HandyJSON



//视频筛选-选项
class ST_FilterOptionSelectView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(close_btn)
        close_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15-(44-28)/2.0)
            make.top.equalToSuperview().offset(22-(44-28)/2.0)
            make.width.height.equalTo(44)
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(close_btn)
        }
        
        
        self.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(15)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var last_selected_option:ST_FilterOptionSelectModel!
    
    func request_data(optionModel:ST_FilterOptionSelectModel){
        
        last_selected_option = optionModel
        
        self.data_array.removeAll()
        
        self.collectionView.reloadData()
        
        self.titleLabel.text = optionModel.title
        
        last_selected_index = nil
        JVrequest(PH.fetchOptionTagsApi,parameters:["search_key":optionModel.optionKey,"type":"all"], success: { (json) in
        
            print("打印所有选项:",json)
            
            if let list = [ModifyUserItemCellModel].deserialize(from: json["data"].rawString() ?? "") as? [ModifyUserItemCellModel]{
                
            var array = [ModifyUserItemCellModel]()
            
            for (idx,item) in list.enumerated(){
                
                if let selectedId = optionModel.selectedId,item.id == selectedId{
                    var  a = item
                    a.isSelected = true
                    self.last_selected_index = idx
                    array.append(a)
                }else{
                    array.append(item)
                }
            }
            
           self.data_array = array
            
            self.collectionView.reloadData()
        }
            
        }) { (code, err) in
            
            print("0------,",err)
            
        }
        
        
    }
//    MARK: - Event
    
    var close_click_closure:((ST_FilterOptionSelectModel?)->())?
    @objc func close_click_handle(){
        
        guard let idx = self.last_selected_index else {
            close_click_closure?(nil)
            return
        }
        
        let m = self.data_array[idx]
        if last_selected_option.selectedId != m.id{
            last_selected_option.selectedText = m.title
            last_selected_option.selectedId = m.id
            
            close_click_closure?(last_selected_option)
            
        }else{
            close_click_closure?(nil)
        }
    }
    
//    MARK: - Properties

    lazy var close_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_返回")!)
        control.addTarget(self, action: #selector(close_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    lazy var titleLabel:UILabel = {
        let control = UILabel.init()
//        control.text = "向我展示"
        control.textColor = Color.init(hexString: "#333333")
//        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    var last_selected_index:Int?
    
    var data_array = [ModifyUserItemCellModel]()
    
    lazy var itemWidth:CGFloat = {
        return ScreenWidth
    }()
    
    lazy var itemHeight = 65.cgFloat
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight)
   
        layout.minimumLineSpacing = 0
        //        layout.minimumInteritemSpacing = 14
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 30 : 20 + 20
        
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.register(cellWithClass: ModifyUserItemCell.self)
        
        collection.delegate = self
        
        collection.dataSource = self
        
        collection.alwaysBounceVertical = true
        
        collection.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            collection.contentInsetAdjustmentBehavior = .never
        }
        return collection
    }()
    
    

}


extension ST_FilterOptionSelectView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ModifyUserItemCell.self, for: indexPath)
        
        cell.bind(model: data_array[indexPath.row])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        if indexPath.row != last_selected_index{
            
            if let lastIdx = last_selected_index {
                
                self.data_array[lastIdx].isSelected = false
            }
            
            self.data_array[indexPath.row].isSelected = true
            
            last_selected_index = indexPath.row
            
            self.collectionView.reloadData()
            
            close_click_handle()
            
        }

    }

}

